﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using LdExpress;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected string ContainerPage = "./Ports.aspx";
    protected string strCondition = "";
    protected int NumOfItemsPerPage = 25;
    protected string strPager = "";
    protected string strIDs = "";
    protected string strError = "";
    protected string strMess = "";
    protected int nPermissions = 0;
    protected int nPage = 1;
    protected string strPageID = "page_number";
    protected string strLetter = "letter";
    protected string strAlphaBet = "";
    string strChar = "";
    string strExcluded = "PortsID";
    protected string strPartQuery = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            if (Request.QueryString[strLetter] != null)
            {
                strChar = Request.QueryString[strLetter].ToString();
                strCondition = " AND tbl_Ports.Name like '" + strChar + "%'";
            }
        }
        catch
        {
            strChar = "";
        }

        try
        {

            if (Request.QueryString[strPageID] != null)
                nPage = int.Parse(Request.QueryString[strPageID]);
        }
        catch
        {
            nPage = 1;
        }
        if (nPage <= 0) nPage = 1;

        if ((Session["logined_id"] != null) && (int.Parse(Session["ports"].ToString()) > 0))
        {
            if (Session["Ports"] != "") nPermissions = int.Parse(Session["Ports"].ToString());
            if (nPermissions <= 0) Response.Redirect("Login.aspx");
        }
        else
            Response.Redirect("Login.aspx");
        if (Session["sesserchRegion"] == null) Session["sesserchRegion"] = "";
        if (Session["sesCountrySeach"] == null) Session["sesCountrySeach"] = "";
        if (Session["PortSerAreaCodeSearch"] == null) Session["PortSerAreaCodeSearch"] = "";
        if (!Page.IsPostBack)
        {
            txtRegionSearch.Text = Session["sesserchRegion"].ToString();
            txtCountrySearch.Text = Session["sesCountrySeach"].ToString();
            txtServiceAreaSearch.Text = Session["PortSerAreaCodeSearch"].ToString();
            CommonFunctions.GetAllQueryString(Request, "", "action;PortsID", out strPartQuery);
            if (Request.QueryString["action"] == "delete" && nPermissions >= 9)
            {
                Ports obj = new Ports();
                obj.ID = long.Parse(Request.QueryString["PortsID"]);
                obj.Load(GV.cn, GV.trans);
                // Re write File Post
                string strFileName = Server.MapPath("./") + "\\Assets\\Js\\Ports.js";

                StreamReader sr = new StreamReader(strFileName, System.Text.Encoding.UTF8);
                string strName = sr.ReadToEnd();
                sr.Close();

                string strNameRemove = "\"" + obj.Name.Trim() + "\",";
                strName = System.Text.RegularExpressions.Regex.Replace(strName, strNameRemove, "");
                strNameRemove = "\"" + obj.Name.Trim() + "\"";
                strName = System.Text.RegularExpressions.Regex.Replace(strName, strNameRemove, "");
                StreamWriter sw;
                sw = new StreamWriter(strFileName, false);
                sw.Write(strName);
                sw.Close();
                obj.Delete(GV.cn, GV.trans);
                Response.Redirect("Ports.aspx" + strPartQuery);
            }
            else
            {
                if (Request.QueryString["custID"] != null)
                {
                }
                if (Request.QueryString["PortsID"] != null)
                {
                    loadPorts();
                }
            }
            LoadDropDownCountry();
            LoadDropDownServiceArea();
            #region Build List
            int nNumOfPages = 0;

            DataTable dtList;
            if (nPermissions == 1) NumOfItemsPerPage = 125;
            BuildList(strCondition, NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
            if (nPage > nNumOfPages) nPage = 1;
            if (nPermissions > 1)
            {
                rptData.DataSource = dtList;
                rptData.DataBind();
            }
            else
            {
                rptDataView.DataSource = dtList;
                //rptDataView.ItemDataBound += new RepeaterItemEventHandler(rptDataView_ItemDataBound);
                rptDataView.DataBind();
            }
            #endregion
            #region Build Pager
            CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
            #endregion
            CommonFunctions.BuildAphabetSearch(Request, ContainerPage, strLetter, strChar, strExcluded, out strAlphaBet);
        }

    }
    protected void loadPorts()
    {
        Ports obj = new Ports();
        obj.ID = long.Parse(Request.QueryString["PortsID"]);
        obj.Load(GV.cn, GV.trans);
        txtPorts.Text = HttpUtility.HtmlDecode(obj.Name);
        txtCode.Text = HttpUtility.HtmlDecode(obj.Code);
        if (obj.IsLocalUsed == 1) LocalUsed.Checked = true;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        strError = "";
        strMess = "";
        if (txtPorts.Text.Trim().Length > 0)
        {
            CommonFunctions.GetAllQueryString(Request, "", "action;PortsID", out strPartQuery);
            Ports obj = new Ports();
            obj.ID = -1;
            if (Request.QueryString["PortsID"] != null)
            {
                obj.ID = long.Parse(Request.QueryString["PortsID"]);
                obj.Load(GV.cn, GV.trans);
            }
            obj.Name = txtPorts.Text.Trim();
            string strCcatCode = "";
            if (txtCode.Text != "")
                obj.Code = txtCode.Text;
            else
            {
                strCcatCode = CommonFunctions.UnicodeToPlain(obj.Name.Trim()).Replace(" ", "-");
                strCcatCode = System.Text.RegularExpressions.Regex.Replace(strCcatCode, @"[^\w\.-]", "");
                strCcatCode = Ports.GetUniqueCode(obj.ID, strCcatCode, GV.cn, GV.trans).ToLower();
                obj.Code = strCcatCode;
            }
            obj.CountryCode = ddCountryCode.SelectedValue;
            obj.ServiceAreaCode = ddServiceArea.SelectedValue;
            obj.LastUpdate = DateTime.Now;
            if (LocalUsed.Checked)
                obj.IsLocalUsed = 1;
            else
                obj.IsLocalUsed = 0;
            if (strError == "")
            {
                obj.Save(GV.cn, GV.trans);
            }
            DataSet ds = null;
            string sqlCommand = "select Name from tbl_Ports order by Name;";
            ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
            string strName = "";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (strName.Length > 0) strName += ",";
                strName += "\"" + dr["Name"].ToString().Trim() + "\"";
            }
            string strCountFile = Server.MapPath("./") + "\\Assets\\Js\\Ports.js";

            StreamWriter sw;

            strName = "var ports = [" + strName + "];";
            sw = new StreamWriter(strCountFile, false);
            sw.Write(strName);
            sw.Close();
            Response.Redirect("Ports.aspx" + strPartQuery);
        }
    }

    private void BuildList(string strCondition, int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out DataTable dtList, MySqlConnection cn, MySqlTransaction trans)
    {
        DataSet ds = null;
        dtList = new DataTable();
        dtList.Columns.Add("Sort");
        dtList.Columns.Add("Index");
        dtList.Columns.Add("Name");
        dtList.Columns.Add("Code");
        dtList.Columns.Add("Country");
        dtList.Columns.Add("Region");
        dtList.Columns.Add("ServiceAreaCode");
        dtList.Columns.Add("Action");
        //Get List by SoIDs
        nNumOfPages = 0;

        if (Session["sesCountrySeach"] != null && Session["sesCountrySeach"].ToString().Trim().Length > 0)
            strCondition += " AND tblCountry.CountryName ='" + DBModule.RefineString(Session["sesCountrySeach"].ToString().Trim()) + "'";
        if (Session["sesserchRegion"] != null && Session["sesserchRegion"].ToString().Trim().Length > 0)
            strCondition += " AND tbRegion.Name='" + DBModule.RefineString(Session["sesserchRegion"].ToString().Trim()) + "'";
        if (Session["PortSerAreaCodeSearch"] != null && Session["PortSerAreaCodeSearch"].ToString().Trim().Length > 0)
            strCondition += " AND ServiceAreaCode='" + DBModule.RefineString(Session["PortSerAreaCodeSearch"].ToString().Trim()) + "'";
        if (strCondition == "") strCondition = "All";
        Ports.GetList(strCondition, "tbl_ports.Name", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

        string strAllQueryString = "";

        foreach (string strKey in Request.QueryString.AllKeys)
        {
            if (strKey != null)
            {
                if ((strKey.ToLower() != "action") && (strKey.ToLower() != "id"))
                    strAllQueryString = strAllQueryString + "&" + strKey + "=" + Request.QueryString[strKey].ToString();
            }
        }

        if (strAllQueryString.Length >= 1)
            strAllQueryString = strAllQueryString.Substring(1);

        if (ds != null)
        {
            int count = 0;
            if (Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "")
            {
                int pagenumber = 1;
                try
                {
                    pagenumber = int.Parse(Request.QueryString["page_number"]);
                    count = NumOfItemsPerPage * (pagenumber - 1);
                }
                catch { count = 0; }
            }
            foreach (DataRow dr in ds.Tables[0].Rows)
            {

                count++;
                string strSTT = dr["Sort"].ToString();
                string strIndex = count.ToString();
                string strName = dr["Name"].ToString();
                string strTitle = "";
                if (dr["LastUpdate"].ToString() != "")
                {
                    strTitle = "title=\"" + DateTime.Parse(dr["LastUpdate"].ToString()).ToString("dd - MM - yyyy") + "\"";
                    strName = "<span title=\"" + DateTime.Parse(dr["LastUpdate"].ToString()).ToString("dd - MM - yyyy") + "\">" + dr["Name"].ToString() + "</span>";
                }
                if (nPermissions >= 3)
                    strName = "<a " + strTitle + " href=\"Ports.aspx?PortsID=" + dr["ID"].ToString() + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "&page_number=" + Request.QueryString["page_number"].ToString() : "") +
                        ((Request.QueryString["letter"] != null && Request.QueryString["letter"].ToString() != "") ? "&letter=" + Request.QueryString["letter"].ToString() : "") +
                        "\">" + dr["Name"].ToString() + "</a>";
                string strCode = dr["Code"].ToString();
                string strCountry = dr["CountrySourceName"].ToString();
                string strRegion = dr["RegionSourceName"].ToString();
                string strServiceAreaCode = dr["ServiceAreaCode"].ToString();

                if (dr["LastUpdate"].ToString() != "")
                {
                    strCountry = "<span title=\"" + DateTime.Parse(dr["LastUpdate"].ToString()).ToString("dd - MM - yyyy") + "\">" + dr["CountrySourceName"].ToString() + "</span>";
                }
                string strAction = "";
                string strTemp = "";
                strTemp = dr["Name"].ToString();
                strTemp = strTemp.Replace("'", "\\'");

                if (nPermissions >= 3)
                    strAction = "<a href=\"Ports.aspx?PortsID=" + dr["ID"].ToString() + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "&page_number=" + Request.QueryString["page_number"].ToString() : "") +
                                ((Request.QueryString["letter"] != null && Request.QueryString["letter"].ToString() != "") ? "&letter=" + Request.QueryString["letter"].ToString() : "") +
                                "\">Edit</a>";
                if (nPermissions > 7)
                    strAction += " - <a href=\"javascript:doDelete('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(strTemp) + "')\">" + "Xóa</a>";
                string[] strValues = new string[] { strSTT, strIndex, strName, strCode, strCountry, strRegion, strServiceAreaCode, strAction };
                dtList.Rows.Add(strValues);
            }
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Session["sesCountrySeach"] = txtCountrySearch.Text.ToString().Trim();
        Session["sesserchRegion"] = txtRegionSearch.Text.ToString();
        if (txtServiceAreaSearch.Text.Length > 0)
            Session["PortSerAreaCodeSearch"] = hidServiceAreaSearch.Value;
        else
            Session["PortSerAreaCodeSearch"] = "";
        #region Build List
        int nNumOfPages = 0;
        if (nPermissions == 1) NumOfItemsPerPage = 125;
        DataTable dtList;
        BuildList(strCondition, NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
        if (nPage > nNumOfPages) nPage = 1;
        if (nPermissions > 1)
        {
            rptData.DataSource = dtList;
            rptData.DataBind();
        }
        else
        {
            rptDataView.DataSource = dtList;
            //rptDataView.ItemDataBound += new RepeaterItemEventHandler(rptDataView_ItemDataBound);
            rptDataView.DataBind();
        }
        #endregion
        #region Build Pager
        CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
        CommonFunctions.BuildAphabetSearch(Request, ContainerPage, strLetter, strChar, strExcluded, out strAlphaBet);
        #endregion
    }
    protected void LoadDropDownCountry()
    {
        DataSet ds;
        Countries.DoSearch("", "CountryName", out ds, GV.cn, GV.trans);
        DataTable dt = ds.Tables[0];
        ddCountryCode.DataSource = dt;
        ddCountryCode.DataValueField = dt.Columns["CountryCode"].ToString();
        ddCountryCode.DataTextField = dt.Columns["CountryName"].ToString();
        ddCountryCode.DataBind();
        ddCountryCode.Items.Insert(0, new ListItem("-- Select --", "0"));
        if (Request.QueryString["PortsID"] != null)
        {
            Ports obj = new Ports();
            obj.ID = long.Parse(Request.QueryString["PortsID"].ToString());
            obj.Load(GV.cn, GV.trans);
            if (ddCountryCode.Items.FindByValue(obj.CountryCode.ToString()) != null)
                ddCountryCode.SelectedValue = obj.CountryCode.ToString();
        }
    }
    protected void LoadDropDownServiceArea()
    {
        DataSet ds;
        ServiceAreas.DoSearch("", "Name ASC", out ds, GV.cn, GV.trans);
        DataTable dt = ds.Tables[0];
        ddServiceArea.DataSource = dt;
        ddServiceArea.DataValueField = dt.Columns["Code"].ToString();
        ddServiceArea.DataTextField = dt.Columns["Code"].ToString();
        ddServiceArea.DataBind();
        ddServiceArea.Items.Insert(0, new ListItem("-- Select --", ""));
        if (Request.QueryString["PortsID"] != null)
        {
            Ports obj = new Ports();
            obj.ID = long.Parse(Request.QueryString["PortsID"].ToString());
            obj.Load(GV.cn, GV.trans);
            if (ddServiceArea.Items.FindByValue(obj.ServiceAreaCode.ToString()) != null)
                ddServiceArea.SelectedValue = obj.ServiceAreaCode.ToString();
        }
    }
    protected int counter = 0;
    protected int columnCount = 5;
    private void rptDataView_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Separator)
            if ((++counter % columnCount) != 0)
                e.Item.Visible = false;
    }

}
